﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace WgrusSetup.Tools
{
    public class ConnectionStringEditor
    {
        private XDocument config;

        public ConnectionStringEditor()
        {
        }

        public void LoadConfig(string appconfigPath)
        {
            TextReader reader = new StreamReader(appconfigPath);
            config = XDocument.Load(reader);
            reader.Close();
        }

        public void UpdateEntityFrameworkConnection(string server, string database)
        {
            var connectionStrings = config.XPathSelectElement("//connectionStrings");

            foreach (var connectionString in connectionStrings.Elements())
            {
                if (connectionString.Attribute("connectionString").Value.Contains("metadata"))
                {
                    var entityBuilder = new EntityConnectionStringBuilder(connectionString.Attribute("connectionString").Value);
                    var cb = new SqlConnectionStringBuilder(entityBuilder.ProviderConnectionString);
                    cb.DataSource = server;
                    cb.InitialCatalog = database;
                    entityBuilder.ProviderConnectionString = cb.ConnectionString;
                    connectionString.Attribute("connectionString").Value = entityBuilder.ToString();
                }
            }
        }

        public void SaveConfig(string appconfigPath)
        {
            TextWriter reader = new StreamWriter(appconfigPath, false);
            config.Save(reader);
            reader.Flush();
            reader.Close();
        }

    }
}
